﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using 自定义RestfulApi.Model;

namespace 自定义RestfulApi.BaseController
{
    public class ResultWrapperFilter : ActionFilterAttribute
    {
        public override void OnResultExecuting(ResultExecutingContext context)
        {
            var responseResult = new ResultfulModel<object>();
            if (context.Result is ObjectResult)
            {
                var objectResult = context.Result as ObjectResult;
                responseResult.Status = context.HttpContext.Response.StatusCode;
                responseResult.TimeStamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString();
                if (objectResult?.Value == null)
                {
                    responseResult.Message = "错误";
                }
                else
                {
                    responseResult.Message = "请求成功";
                    responseResult.Data = objectResult.Value;
                }
                context.Result = new ObjectResult(responseResult);
            }
        }
    }
}
